<?php
namespace App\Http\Controllers\WebApi;

use App\Common\ErrorCode\ErrorCode;
use App\Common\Output\JsonOutput;
use App\Exceptions\BusinessException;
use App\Http\Controllers\BaseController as Controller;
use App\Jobs\Fun;
use App\Models\Admin\UserAccessModel;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use App\Models\Admin\YzmModel;
use function PHPSTORM_META\type;
//use   PHPSTORM_META\type;

class BaseController extends Controller
{
    protected $web_access = ''; //接口调用权限

    /**
     * 接口基本控制器
     */

    public function __construct()
    {
        $this->app_access=Fun::app_access;
        parent::__construct();
//        $this->web_access = $this->getApiAccess(2);  //测试时候先注释
    }

    /**
     * 返回到手机端的数据格式
     * 制作者：九哥
     * code错误代号，dataArr返回的数据
     * code：0操作成功，
     */
    public function toJson($code=0,$dataArr=array())
    {
        $msgArr = array(
            0 => '操作成功', -1 => '接口权限错误', -2 => '参数错误',
            -3 => '没有数据', -4 => '用户已存在', -5 => 'TOKEN错误',
            -7 =>'验证码错误',//zwp,增加一个配置
            -8 =>'用户类型不能更改', -9 =>'用户未登录', -10 =>'数据更新失败',
            -99 =>'非法请求',
            -100 => '操作失败',
        );
        $json = array(
            'code' => $code,
            'msg' => $msgArr[$code].'！',
        );
        if ($dataArr) { $json['data'] = $dataArr; }
        return $json;
    }

    public function output($data = [], $msg = "ok",
                           $code = 200, $status = 200,
                           array $headers = [], $options = 0)
    {
        $headers['Access-Control-Allow-Origin'] = '*';
        return response()->json(compact('msg', 'code', 'data'), $status, $headers, $options);
    }


    /**
     * @param array $data
     */
    public function success(array $data = [])
    {
        JsonOutput::success($data);
    }

    /**
     * @param array $data
     */
    public function error(int $code = 0, string $message = "")
    {
        JsonOutput::error($code, $message);
    }


    /**
     * @param Request $request
     * @param array $rules
     * @throws BusinessException
     */
    public function webParamValidate(Request $request, $rules = [])
    {
        try{
            $this->validate($request, $rules);
        }catch (ValidationException $exception) {
            throw new BusinessException(ErrorCode::ERROR_PARAM, '参数错误：'.array_values($exception->errors())[0][0]);
        }catch (\Exception $exception){
            throw new BusinessException(ErrorCode::ERROR_SERVER_UNKNOWN, '服务端校验参数时发生错误');
        }
    }
    /**
     * 发送验证码
     */
    public function sendYzm(Request $request)
    {
        //   return $this->toJson(0); //先屏蔽验证码
        $phone = $request->phone;
        if ($request->app_access != $this->web_access) {
            return $this->toJson(-1);
        }
        if (!preg_match('/^1[34578]\d{9}$/', $phone)) {
            return $this->toJson(-8);
        }
        $resYzm = $this->getYzm($phone);
        if ($resYzm) {
            return $this->toJson(-6, [], '刚刚已经发送给验证码');
        }
//        $code = Utility::getRandStr(rand(4,6),0);
        $code = Utility::getRandStr(4, 0);
        /// YzmModel::deleted();
        $dataArr = array(
            'phone' => $phone,
            'code' => $code,
            'created_at' => time(),
        );
        $lastId = YzmModel::insertGetId($dataArr);
        $sms = new Sms();
        $msg = "【美策】验证码{$code}，您正在进行美策平台的账号注册，有效时间30分钟身份验证，打死不要告诉别人哦！";
        /*
        $resSms = $sms->sendSMS($phone, $msg);
        $resSms = json_decode($resSms, true);
        if (empty($resSms) || !empty($resSms['errorMsg'])) {
            return $this->toJson(-11);
        }*/
        YzmModel::where('id', $lastId)->update(array('status' => 2));
        return $this->toJson(1, [], '万能验证码是:1234;临时关闭短信发送,短信内容是:' . $msg);


        return $this->toJson(0);
    }
    /**
     * 获取验证码
     */
    public function getYzm($phone)
    {
        ///  return true; //先取消验证码验证
//        $start = strtotime(date('Ymd').'000000');
//        $end = strtotime(date('Ymd').'235959');
        $model = YzmModel::where('phone', $phone)
            ->where('status', 2)
//            ->where('created_at','>',$start)
//            ->where('created_at','<=',$end)
            ->where('created_at', '>', time() - 60 * 30)
            ->first();
        return $model ? $model->code : '';
    }

    /**
     * 通过TOKEN，获取UID
     */
    public function getUidByToken($token)
    {
        return UserAccessModel::getUidByToken($token);
    }
}